package at.fhj.itm11.forum.service;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import at.fhj.itm11.forum.data.PostRepository;
import at.fhj.itm11.forum.data.RatingRepository;
import at.fhj.itm11.forum.model.Post;
import at.fhj.itm11.forum.model.Rating;

@Stateless
public class RatingService {
    @Inject
    private EntityManager em;
    
    @Inject
    private PostRepository postRepo;
    
    @Inject
    private RatingRepository ratingRepo;
    
    public void rate(Rating r) {
    	
    	Long postId = r.getPost().getId();
    	Post associatedPost = postRepo.findById(postId);
    	Rating ratingFromDb;
    	
    	try {
    		ratingFromDb = ratingRepo.findRatingByRaterAndPost(r.getUser().getId(), associatedPost.getId());
    		//update rating in database
    		ratingFromDb.setPositiveRating(r.isPositiveRating());
    		em.merge(ratingFromDb);
    	}
    	catch(NoResultException ex) {
    		//insert rating in database
        	r.setPost(associatedPost);
        	em.persist(r);
    	}
    }
    
    public int[] getRatingStatistics(Long postId) {

		long positiveRatingCount = ratingRepo.findPositiveRatingCountForPost(postId);
		long negativeRatingCount = ratingRepo.findNegativeRatingCountForPost(postId);
		
		int[] result = new int[2];
		long totalRatings;
		if((totalRatings = positiveRatingCount + negativeRatingCount) == 0) {
			result[0] = 0;
			result[1] = 0;
		}
		else {
			result[0] = (int)((positiveRatingCount * 100f) / totalRatings);
			result[1] = (int)((negativeRatingCount * 100f) / totalRatings);
		}
		
		return result;
    }
}
